package com.itaq.cheetah.serviceA.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itaq.cheetah.serviceA.config.exception.CustomException;
import com.itaq.cheetah.serviceA.dao.ISsoClientDetailMapper;
import com.itaq.cheetah.serviceA.model.dto.SsoClientDetailDTO;
import com.itaq.cheetah.serviceA.model.entity.SsoClientDetail;
import com.itaq.cheetah.serviceA.service.ISsoClientDetailService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 单点登录接口Service业务层处理
 *
 * @author cheetah
 * @date 2023-05-20
 */
@Service
public class SsoClientDetailServiceImpl extends ServiceImpl<ISsoClientDetailMapper, SsoClientDetail> implements ISsoClientDetailService {

    @Override
    public SsoClientDetail saveClient(SsoClientDetailDTO ssoClientDetailDTO) {
        SsoClientDetail ssoClientDetail = this.baseMapper.selectOne(new LambdaQueryWrapper<SsoClientDetail>()
                .eq(SsoClientDetail::getPlatformName, ssoClientDetailDTO.getPlatformName()));
        if(ssoClientDetail == null){
            ssoClientDetail = new SsoClientDetail();
            ssoClientDetail.setPlatformName(ssoClientDetailDTO.getPlatformName());
            ssoClientDetail.setPlatformId(RandomStringUtils.randomAlphanumeric(8));
            ssoClientDetail.setPlatformSecret(RandomStringUtils.randomAlphanumeric(60));
            ssoClientDetail.setSsoUrl(ssoClientDetailDTO.getSsoUrl());
            if(StringUtils.isNotEmpty(ssoClientDetailDTO.getEncryptType())) {
                ssoClientDetail.setEncryptType(ssoClientDetailDTO.getEncryptType());
            }
            this.baseMapper.insert(ssoClientDetail);
            return ssoClientDetail;
        }else{
            throw new CustomException("该应用名称已存在，请更换应用名称");
        }
    }
}
